from flask import Blueprint, jsonify, request
import json
from db import db1

bp_courses = Blueprint('courses', __name__)


def xtree(data):
    if not data:
        return data
    else:
        tree = {}
        list = []
        for i in data:
            tree[i['id']] = i
        for j in data:
            if j['pid'] == 0:
                list.append(j)
            else:
                if 'son' not in tree[j['pid']]:
                    tree[j['pid']]['son'] = []
                tree[j['pid']]['son'].append(j)
        return list


@bp_courses.route('/cates', methods=['POST', 'GET'])
def cates():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['params']:
            sql = '''insert into cates values (0,'%s',%d,%s)''' % (data['name'], int(data['pid']), data['params'])
        else:
            sql = '''insert into cates values (0,'%s',%d,'%s')''' % (data['name'], int(data['pid']), '')
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = '''select * from cates'''
        res = db1.findall(sql)
        print(res)
        data = xtree(res)
        return jsonify({'code': 200, 'list': data})


@bp_courses.route('/pageM', methods=['GET'])
def pageM():
    if request.method == 'GET':
        capge = request.args.get('cpage')
        page_size = 3
        start = (int(capge) - 1) * page_size
        sql = 'select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id asc limit %d,%d' % (
            start, page_size)
        sql2 = '''select count(id) from cates'''
        res = db1.findall(sql)
        total = db1.findone(sql2)
        return jsonify({'code': 200, 'list': res, 'total': total['count(id)']})


import time


@bp_courses.route('/tea', methods=['GET'])
def tea():
    if request.method == 'GET':
        time.sleep(0.1)
        sql = '''select * from teacher'''
        res = db1.findall(sql)
        return jsonify({'code': 200, 'tea': res})


@bp_courses.route('/cate', methods=['GET'])
def cate():
    if request.method == 'GET':
        id = request.args.get('id')
        sql = '''select params from cates where id=%d ''' % (int(id))
        res = db1.findone(sql)

        return jsonify({'code': 200, 'params': res['params']})


@bp_courses.route('/courses', methods=['POST', 'GET'])
def courses():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['params']:
            sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = request.args.get('cpage')
        if cpage:
            page_size = 2
            start = (int(cpage) - 1) * page_size
            sql = '''select c.id,c.title,c.pic,c.descrip,c.status,ca.name as caname from courses as c left join cates as ca on c.pid = ca.id limit %d,%d''' % (
                start, page_size)
        else:
            sql = '''select id,title from courses'''
        res = db1.findall(sql)
        sql2 = '''select count(id) from courses'''
        total = db1.findone(sql2)
        return jsonify({'code': 200, 'list': res, 'total': total['count(id)']})


from utils.comm import qntoken


@bp_courses.route('/qn', methods=['GET'])
def qn():
    if request.method == 'GET':
        token = qntoken()
        return jsonify({'code': 200, 'qntoken': token})


import os


@bp_courses.route('/addmp4', methods=['POST'])
def addmp4():
    if request.method == 'POST':
        file = request.files['file']
        courses_id = str(request.form['course_id'])
        print(courses_id)
        path = './static/upload/' + courses_id
        if not os.path.exists(path):
            os.mkdir(path)
        file.save(os.path.join(path, file.filename))
        return jsonify({'code': 200, 'url': path + '/' + file.filename})


@bp_courses.route('/jie', methods=['POST', 'GET'])
def jie():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = '''insert into jie values(0,"%s",%d,"%s")''' % (data['name'], data['course_id'], data['video_url'])
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = int(request.args.get('id'))
        sql = '''select j.id,j.name,j.video_url,c.title as ctitle from jie as j left join courses as c on j.course_id = c.id where course_id = %d''' % (
            id)
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})
